package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.AuditNode;
import com.sl.au.entity.AuditRoot;
import com.sl.au.entity.MyTask;
import com.sl.au.entity.User;
import com.sl.au.service.ActivitiService;
import com.sl.au.service.AuditNodeService;

/**
 * 审批任务总控制器
 * 
 * @author Neil
 *
 */
@RestController
@RequestMapping(value = "/ui/task")
public class TaskController extends BaseController {

	@Autowired
	private AuditNodeService auditNodeService;


	@Autowired
	private ActivitiService activitiService;

	
	/**
	 * 列出当前用户的审批任务
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView getMyTaskList(HttpServletRequest request) {
		ModelAndView mv = this.createLayoutView("task/taskindex");
		Account a = this.getMyAccount();
		String userId = null;
		if (null != a)
			userId = a.getUser().getId();
		if (null != userId) {
			Map<String, Object> map = new HashMap<String, Object>();
			List<MyTask> tasks = activitiService.getMyTasksByUser(userId);
			mv.addObject("tasks", tasks);
		}

		return mv;
	}

	/**
	 * 列出当前用户的审批任务JSON
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "json", method = RequestMethod.GET)
	public Map<String, Object> getMyTaskListJSON(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		String userId = null;
		if (null != a)
			userId = a.getUser().getId();
		if (null != userId) {
			map = new HashMap<String, Object>();
			List<MyTask> tasks = activitiService.getMyTasksByUser(userId);
			String key = request.getParameter("key");
			if (StringUtils.hasText(key)) {
				tasks = tasks.stream().filter(
						task -> task.getProcessDefinitionName().contains(key) || task.getStarterName().contains(key)
						|| task.getTaskTitle().contains(key))
						.collect(Collectors.toList());
			}
			map.put("data", tasks);
		}

		return map;
	}

	/**
	 * 完成本次审批，结点往下走
	 * 
	 * @return
	 */
	@RequestMapping(value = "{taskId}", method = RequestMethod.POST)
	public Map<String, Object> completeTask(@PathVariable String taskId, @RequestBody AuditNode auditNode) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", -1);
		Map<String, String> formData = new HashMap<>();
		auditNode.setAuditor(this.getMyAccount().getUser());

		formData.put("auditAdvice", auditNode.getAuditAdvice());
		formData.put("auditState", auditNode.getAuditState());
		this.activitiService.submitTaskFormData(taskId, formData, auditNode);
		map.put("code", 0);
		return map;
	}

	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("task-key");
		String userId = this.getMyAccount().getUser().getId();
		List<MyTask> tasks = activitiService.getMyTasksByUser(userId);
		List<MyTask> data = new ArrayList<MyTask>();
		if (null != tasks && tasks.size() > 0) {
			for (int i = start; i < start + 5; i++) {
				if (i == tasks.size())
					break;
				data.add(tasks.get(i));
			}
		}

		int count = tasks.size();
		map.put("data", data);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 返回察看审批节点对话框的内容
	 * 
	 * @param entity
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "audit-nodes/{entity}/{id}", method = RequestMethod.GET)
	public ModelAndView getAuditNodes(@PathVariable String entity, @PathVariable String id) {
		ModelAndView mv = this.createSingleView("task/audit-node");
		String title = "";
		String pInstId = null;
		List<AuditNode> nodes = new ArrayList<>();
		int code = -1;
		switch (entity) {
		
		}
		if (title.length() > 0) {
			nodes = auditNodeService.getAll(pInstId, id);
			code = 0;
		}

		mv.addObject("title", title);
		mv.addObject("auditnodes", nodes);
		return mv;
	}

	/**
	 * 返回察看审批节点对话框的内容JSON
	 * 
	 * @param entity
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "audit-nodes/{entity}/{id}/json", method = RequestMethod.GET)
	public Map<String, Object> getAuditNodesJSON(@PathVariable String entity, @PathVariable String id) {
		Map<String, Object> map = new HashMap<>();
		String title = "";
		String pInstId = null;
		List<AuditNode> nodes = new ArrayList<>();
		int code = -1;
		switch (entity) {
		
		}
		if (title.length() > 0) {
			nodes = auditNodeService.getRepository().getNodesById(pInstId, id);
			code = 0;
		}
		map.put("data", nodes);
		return map;
	}

	/**
	 * 撤销审批流程实例
	 * 
	 * @param auditNode
	 * @return
	 */
	@RequestMapping(value = "cancel/{entity}/{id}", method = RequestMethod.POST)
	public Map<String, Object> cancelPInst(@PathVariable String entity, @PathVariable String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("code", -1);

		String pInstId = null;
		switch (entity) {

		}

		map.put("code", 0);
		return map;
	}

	// 移动端得到我发起已完成的审批
	@RequestMapping(value = "/getmystarts", method = RequestMethod.GET)
	Map<String, Object> getMystarts(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		User user = this.getMyAccount().getUser();
		String key = request.getParameter("key");
		List<MyTask> list = this.activitiService.getStartedTasks(user, key);
		if (StringUtils.hasText(key)) {
			list = list.stream().filter(
					task -> task.getProcessDefinitionName().contains(key) || task.getStarterName().contains(key)
					|| task.getTaskTitle().contains(key))
					.collect(Collectors.toList());
		}
		map.put("data", list);
		map.put("code", 0);
		return map;
	}
	

	// 移动端得到我发起已完成的审批的数量
	@RequestMapping(value = "/getMystartsNumber/{userId}", method = RequestMethod.GET)
	Map<String, Object> getMystartsNumber(@PathVariable String userId) {
		Map<String, Object> map = new HashMap<>();
		User user = this.getMyAccount().getUser();
		String key = request.getParameter("key");
		List<MyTask> list = this.activitiService.getStartedTasks(user, key);
		map.put("data", list.size());
		map.put("code", 0);
		return map;
	}

	// 得到我经手完成的审批
	@RequestMapping(value = "/getmyins", method = RequestMethod.GET)
	Map<String, Object> getMyIns(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		User user = this.getMyAccount().getUser();
		String key = request.getParameter("key");
		List<MyTask> list = this.activitiService.getHistoryTasksByUser(user.getId(), key);
		if (StringUtils.hasText(key)) {
			list = list.stream().filter(
					task -> task.getProcessDefinitionName().contains(key) || task.getStarterName().contains(key)
					|| task.getTaskTitle().contains(key))
					.collect(Collectors.toList());
		}
		map.put("data", list);
		map.put("code", 0);
		return map;
	}
	
	// pc得到我经手完成的审批
	@RequestMapping(value = "/pcgetmyins", method = RequestMethod.GET)
	Map<String, Object> pcgetMyIns(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		User user = this.getMyAccount().getUser();
		String key = request.getParameter("key");
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		List<MyTask> list = this.activitiService.getHistoryTasksByUser(user.getId(), key);
		List<MyTask> listNew = new ArrayList<MyTask>();
		if (StringUtils.hasText(key)) {
			list = list.stream().filter(
					task -> task.getProcessDefinitionName().contains(key) || task.getStarterName().contains(key)
					|| task.getTaskTitle().contains(key))
					.collect(Collectors.toList());
		}
		if (list != null) {
			for (int i = start; i < start + length; i++) {
				if (i == list.size()) {
					break;
				}
				listNew.add(list.get(i));
			}
		}
		int count = list.size();
		map.put("data", listNew);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
		
		// pc端得到我发起已完成的审批
		@RequestMapping(value = "/pcgetmystarts", method = RequestMethod.GET)
		Map<String, Object> getpcMystarts(HttpServletRequest request) {
			Map<String, Object> map = new HashMap<>();
			User user = this.getMyAccount().getUser();
			int start = Integer.parseInt(request.getParameter("start"));
			int length = Integer.parseInt(request.getParameter("length"));
			String key = request.getParameter("key");
			List<MyTask> list = this.activitiService.getStartedTasks(user, key);
			List<MyTask> listNew = new ArrayList<MyTask>();
			if (StringUtils.hasText(key)) {
				list = list.stream().filter(
						task -> task.getProcessDefinitionName().contains(key) || task.getStarterName().contains(key)
						|| task.getTaskTitle().contains(key))
						.collect(Collectors.toList());
			}
			if (list != null) {
				for (int i = start; i < start + length; i++) {
					if (i == list.size()) {
						break;
					}
					listNew.add(list.get(i));
				}
			}
			int count = list.size();
			map.put("data", listNew);
			map.put("draw", request.getParameter("draw"));
			map.put("recordsFiltered", count);
			map.put("recordsTotal", count);
			return map;
		}

	// 得到我经手完成的审批的数量
	@RequestMapping(value = "/getMyinsNumber/{userId}", method = RequestMethod.GET)
	Map<String, Object> getMyinsNumber(@PathVariable String userId) {
		Map<String, Object> map = new HashMap<>();
		User user = this.getMyAccount().getUser();
		String key = request.getParameter("key");
		List<MyTask> list = this.activitiService.getHistoryTasksByUser(user.getId(), key);
		map.put("data", list.size());
		map.put("code", 0);
		return map;
	}
}
